package com.lmy.advisor;

import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;

import java.util.Map;

public class ReReadingAdvisor implements BaseAdvisor {

    // 定义重写提示词的模板
    private static final String DEFAULT_USER_TEXT_ADVISE = """
            {re2_input_query}
            Read the question again: {re2_input_query}
            """;

    @Override
    public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
        // todo.. 请求之前，重写提示词
        // 1.获得用户输入文本
        String inputQuery = chatClientRequest.prompt().getUserMessage().getText();
        // 2.定义重复输入模板
        String re2InputQuery = PromptTemplate.builder().template(DEFAULT_USER_TEXT_ADVISE)
                .build()
                .render(Map.of("re2_input_query", inputQuery));
        // 3.复制一份chatClientRequest
        ChatClientRequest.Builder mutate = chatClientRequest.mutate();
        // 4.在原有chatClient对象基础上，只修改提示词并重新构建chatClient对象
        ChatClientRequest chatClientRequest1 = mutate.prompt(Prompt.builder().content(re2InputQuery).build())
                .build();
        // 5.返回新的chatClientRequest
        return chatClientRequest1;
    }

    @Override
    public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
        return chatClientResponse;
    }

    //拦截器执行顺序，顺序越小越靠前
    @Override
    public int getOrder() {
        return 0;
    }
}
